
package com.app.loctracker;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.telephony.SmsManager;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class SMSReceiver extends BroadcastReceiver {

    String lat = "";

    String lan = "";

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Bundle bundle = intent.getExtras();
        DefaultHttpClient httpclient = new DefaultHttpClient();
        Object messages[] = (Object[])bundle.get("pdus");
        SmsMessage smsMessage[] = new SmsMessage[messages.length];
        for (int n = 0; n < messages.length; n++) {
            smsMessage[n] = SmsMessage.createFromPdu((byte[])messages[n]);
        }
        for (int i = 0; i < messages.length; i++) {
            if (smsMessage[i].getMessageBody().equalsIgnoreCase("GPS")) {
                StringBuilder inb = new StringBuilder();
                FileInputStream fis = null;
                try {
                    fis = context.openFileInput("blocatordata.xml");
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                int ch;
                try {
                    while ((ch = fis.read()) != -1)
                        inb.append((char)ch);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String content="";
                Log.v("Data", inb.toString());
                parseXml(inb.toString());// parse the file contents
                if(!lat.equalsIgnoreCase("GPS")){
                    HttpGet httpget = new HttpGet("http://maps.google.com/maps/geo?output=xml&oe=utf-8&ll="+lat+"%2C"+lan+"&key=ABQIAAAAjU0EJWnWPMv7oQ-jjS7dYxSPW5CJgpdgO_s4yyMovOaVh_KvvhSfpvagV18eOyDWu7VytS6Bi1CWxw");
                    try{
                        HttpResponse response = httpclient.execute(httpget);
                        HttpEntity testEntity=response.getEntity();
                        if(testEntity!=null){
                            Log.v("Status Line",response.getStatusLine().toString());
                            content = EntityUtils.toString(testEntity);
                            System.out.println(content);
                        }
                    }catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                        Log.v("ClientProtocolException",e.toString());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        Log.v("IOException",e.toString());
                    }
                    sendSMS(smsMessage[i].getOriginatingAddress(), parseMapData(content));
                }else{
                    sendSMS(smsMessage[i].getOriginatingAddress(), "Sorry! GPS Data not found");
                }
            }
        }
    }

    private void sendSMS(String phoneNumber, String message) {
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, null, null);
    }

    private void parseXml(String data) {
        try {
            InputStream in = new ByteArrayInputStream(data.getBytes());
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(in, null);
            NodeList latn = doc.getElementsByTagName("lat");
            lat = latn.item(0).getTextContent();
            NodeList lann = doc.getElementsByTagName("lan");
            lan = lann.item(0).getTextContent();
            in.close();
        } catch (Throwable t) {
            // Toast.makeText(this, "Exception: "+t.toString(), 2000).show();
            Log.v("Exception", "Exception: " + t.toString());
        }
    }
    
    private String parseMapData(String data){
        String addr="Sorry! Map Data not found";
        try {
            InputStream in = new ByteArrayInputStream(data.getBytes());
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(in, null);
            NodeList address = doc.getElementsByTagName("address");
            addr = address.item(0).getTextContent();
        } catch (Throwable t) {
            Log.v("Exception", "Exception: " + t.toString());
        }
        return addr;
    }
}
